package com.ruitu.router_module.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import androidx.annotation.Nullable;

import com.ruitu.arad.Arad;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;

public class StepService extends Service implements SensorEventListener {
    //当前步数
    private int CURRENT_STEP;

    //传感器
    private SensorManager manager;
    //计步器传感类型
    private static int stepSenor = -1;
    //广播接收
    private BroadcastReceiver mInfoReceiver;
    //未记录前的步数
    private int hasStepCount;
    //上一次的步数
    private int previousStepCount;
    //是否有当天的记录
    private boolean hasRecord;
    //广播
    private BroadcastReceiver receiver;
    private Messenger messenger = new Messenger(new MessageHandler());

    @Override
    public void onCreate() {
        super.onCreate();
        initBroadcastReceiver();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getStepDetector();
            }
        }).start();
    }

    private void getStepDetector() {
        if (manager != null) {
            manager = null;
        }
        manager = (SensorManager) getSystemService(SENSOR_SERVICE);

        if (Build.VERSION.SDK_INT >= 19) {

            addCountStepListener();
        }
    }

    private void addCountStepListener() {
        Sensor counterStep = manager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        Sensor detectorStep = manager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);

        if (counterStep != null) {
            stepSenor = 0;
            manager.registerListener(StepService.this, counterStep, SensorManager.SENSOR_DELAY_NORMAL);
        } else if (detectorStep != null) {
            stepSenor = 1;
            manager.registerListener(StepService.this, detectorStep, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 初始化广播
     */
    private void initBroadcastReceiver() {
        final IntentFilter filter = new IntentFilter();
        //屏幕灭屏广播
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        //关机广播
        filter.addAction(Intent.ACTION_SHUTDOWN);
        //屏幕解锁广播
        filter.addAction(Intent.ACTION_USER_PRESENT);
        //当长按电源键弹出"关机"对话或者锁屏时系统会发生出这个广播
        //example;有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者"关机"对话框上,
        //所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //监听日期变化
        filter.addAction(Intent.ACTION_DATE_CHANGED);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIME_TICK);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    //屏幕灭屏广播
                    case Intent.ACTION_SCREEN_OFF:
                        Logg.i("屏灭了");
                        break;
                    //关机广播
                    case Intent.ACTION_SHUTDOWN:
                        break;
                    //屏幕解锁广播
                    case Intent.ACTION_USER_PRESENT:
                        break;
                    case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
                        Logg.i("要关机了");
                        break;
                    case Intent.ACTION_DATE_CHANGED:
                    case Intent.ACTION_TIME_CHANGED:
                    case Intent.ACTION_TIME_TICK:
                        Logg.i("hasStepCount: " + hasStepCount);
                        Logg.i("previousStepCount: " + previousStepCount);
                        Logg.i("CURRENT_STOP: " + CURRENT_STEP);
                        Arad.bus.post(new EventModel(19112000, hasStepCount + ""));
                        break;
                    default:
                        break;
                }
            }
        };
        registerReceiver(receiver, filter);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (stepSenor == 0) {
            int tempStep = (int) event.values[0];
            if (!hasRecord) {
                hasRecord = true;
                hasStepCount = tempStep;
            } else {
                int thisStepCount = tempStep - hasStepCount;
                CURRENT_STEP += (thisStepCount - previousStepCount);
                previousStepCount = thisStepCount;
            }
        } else if (stepSenor == 1) {
            if (event.values[0] == 1.0) {
                CURRENT_STEP++;
            }
        }

    }

    private class MessageHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    Messenger messenger = msg.replyTo;
                    Message replyMsg = Message.obtain(null, 0);
                    Bundle bundle = new Bundle();
                    bundle.putInt("steps", CURRENT_STEP);
                    replyMsg.setData(bundle);
                    try {
                        messenger.send(replyMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
